#ifndef _PROCESS_POOL_HPP_
#define _PROCESS_POOL_HPP_

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <vector>

#include "Task.hpp"

// 单个信道的描述
class Channel
{
public:
    Channel(int wfd, int id) : _wfd(wfd), _id(id)
    {
        _name = "channel-" + std::to_string(id) + "-" + std::to_string(_wfd);
    }

    // 发送任务
    void Send(int taskcode)
    {
        ssize_t n = write(_wfd, &taskcode, sizeof(taskcode));
        (void)n; // 这样写防止编译报错——定义了n但是没有使用
    }

    std::string GetName() { return _name; }
    int Getwfd() { return _wfd; }
    pid_t Getid() { return _id; }
    ~Channel() {}

private:
    int _wfd;
    pid_t _id;
    std::string _name;
};

// 对多个信道的描述
class ChannelManager
{
public:
    ChannelManager() : _next(0)
    {
    }
    void ChannelInsert(int wfd, pid_t id)
    {
        _channels.emplace_back(wfd, id); // 先调用构造函数构造对象之后进行插入channels
    }
    void PrintChannels()
    {
        for (auto &ch : _channels)
        {
            std::cout << ch.GetName() << std::endl;
        }
    }
    Channel &Select()
    {
        Channel &c = _channels[_next++];
        _next %= _channels.size(); // 防止越界
        return c;
    }
    void CloseChannelWfd()
    {
        for (auto &ch : _channels)
        {
            close(ch.Getwfd());
        }
        std::cout << "关闭此子进程连接到之前管道的所有写端" << std::endl;
        //std::cout << "父进程写端全部关闭" << std::endl;
    }
    void WaitSubProcess()
    {
        for (auto &ch : _channels)
        {
            pid_t id = ch.Getid();
            waitpid(id, nullptr, 0);
        }
        std::cout << "子进程退出信息接收完毕" << std::endl;
    }
    void Close()
    {
        for (auto &ch : _channels)
        {
            close(ch.Getwfd());
            pid_t id = ch.Getid();
            waitpid(id, nullptr, 0);
        }
        // for (int i = _channels.size() - 1; i >= 0; i--)
        // {
        //     close(_channels[i].Getwfd());
        //     pid_t id = _channels[i].Getid();
        //     waitpid(id, nullptr, 0);
        // }
    }
    ~ChannelManager() {}

private:
    std::vector<Channel> _channels;
    int _next; // 标明下一次轮询的下标
};

int gdefaultnum = 5;
// 进程池
class ProcessPool
{
public:
    ProcessPool(int processnum) : _processnum(processnum)
    {
        _tm.TaskRegister(LogView);
        _tm.TaskRegister(Download);
        _tm.TaskRegister(Delete);
    }
    // 子进程的工作
    void Work(int rfd)
    {
        while (true)
        {
            int taskcode = 0;
            ssize_t n = read(rfd, &taskcode, sizeof(taskcode));
            if (n > 0)
            {
                if (n != sizeof(taskcode)) // 虽然读了但是不完整,重新读
                {
                    continue;
                }
                std::cout << "读取成功!" << std::endl;
                std::cout << "子进程[" << getpid() << "]读取到的任务码是 : " << taskcode << std::endl;
                // 执行任务
                std::cout << "执行任务 : " << std::endl;
                _tm.Execute(taskcode);
            }
            else if (n == 0)
            {
                std::cout << "写关, 子进程退出" << std::endl;
                break;
            }
            else
            {
                std ::cout << "读取错误, 子进程退出" << std::endl;
                break;
            }
        }
    }
    bool Create()
    {
        for (int i = 0; i < _processnum; i++)
        {
            // 创建管道
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if (n < 0)
                return false;

            pid_t id = fork();
            if (id < 0)
                return false;
            else if (id == 0)
            {
                close(pipefd[1]);
                _cm.CloseChannelWfd();
                Work(pipefd[0]);
                close(pipefd[0]);
                exit(0);
            }
            else
            {
                close(pipefd[0]);
                // 走到此处已经创建了一个管道和子进程，就要开始添加信道
                _cm.ChannelInsert(pipefd[1], id);
                // close(pipefd[1]);
            }
        }
        return true;
    }
    void Debug()
    {
        _cm.PrintChannels();
    }
    void Run()
    {
        // 选择任务码
        int taskcode = _tm.Taskcode();
        // 轮询方式选择子进程
        auto &c = _cm.Select();
        std::cout << "选择的子进程 : " << c.GetName() << std::endl;
        // 发送任务码
        c.Send(taskcode);
        std::cout << "发送了任务码 : " << taskcode << std::endl;
    }
    void Stop()
    {
        //     //关闭写端 , 即子进程退出
        //     _cm.CloseChannelWfd();
        //     //结束子进程退出信息
        //     _cm.WaitSubProcess();
        _cm.Close();
    }
    ~ProcessPool() {}

private:
    ChannelManager _cm;
    int _processnum;
    TaskManager _tm;
};

#endif